package com.ants.boot.wx.service.impl;

import com.ants.boot.utils.DateUtils;
import com.ants.boot.core.security.utils.SecurityUtils;
import com.ants.boot.wx.dao.WxCheckinMapper;
import com.ants.boot.wx.domain.WxCheckin;
import com.ants.boot.wx.dto.wxcheckin.LastOrNextMonthDto;
import com.ants.boot.wx.service.WxCheckinService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.Date;
import java.util.List;

/**
 * @author 蚂蚁会花呗
 * @date 2022/5/31 10:06
 */
@Service
public class WxCheckinServiceImpl extends ServiceImpl<WxCheckinMapper, WxCheckin> implements WxCheckinService {
    @Override
    public List<WxCheckin> getCurrentMonth() {
        //当前用户登录id
        Integer userId = SecurityUtils.getLoginUser().getUserId();
        QueryWrapper<WxCheckin> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(WxCheckin::getUserId,userId)
                .likeRight(WxCheckin::getCheckDate, DateUtils.formatDate("yyyy-MM",new Date()));
        return this.list(queryWrapper);
    }

    @Override
    public WxCheckin getCurrentDay() {
        Integer userId = SecurityUtils.getLoginUser().getUserId();
        QueryWrapper<WxCheckin> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(WxCheckin::getUserId,userId)
                .eq(WxCheckin::getCheckDate,DateUtils.formatDate("yyyy-MM-dd",new Date()));
        return this.getOne(queryWrapper);
    }

    @Override
    public List<WxCheckin> lastOrNextMonth(LastOrNextMonthDto dto) {
        Integer userId = SecurityUtils.getLoginUser().getUserId();
        QueryWrapper<WxCheckin> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(WxCheckin::getUserId,userId)
                .likeRight(WxCheckin::getCheckDate, dto.getMonthStr());
        return this.list(queryWrapper);
    }

    @Override
    @Transactional
    public boolean addDate() {
        String date = DateUtils.formatDate("yyyy-MM-dd",new Date());
        Integer userId = SecurityUtils.getLoginUser().getUserId();
        WxCheckin check = getOneByUserIdAndCheckDate(userId,date);
        if (check == null){
            WxCheckin wxCheckin = new WxCheckin();
            wxCheckin.setCheckDate(LocalDate.now());
            wxCheckin.setUserId(userId);
            return this.save(wxCheckin);
        }
        return true;
    }

    private WxCheckin getOneByUserIdAndCheckDate(Integer userId,String checkDate){
        QueryWrapper<WxCheckin> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(WxCheckin::getUserId,userId)
                .eq(WxCheckin::getCheckDate,checkDate);
        return this.getOne(queryWrapper);
    }


}
